from sqlalchemy import *
from core.db import *
from core import *
import re

class qPage(object):
	def prev(self):
		return page_query.get(self.page_number-1)
	def next(self):
		return page_query.get(self.page_number+1)
	
class qPageNumber(object):
	def __init__(self,qAye,number,type):
		self.aye_id = qAye.id
		self.page_number = translation
		self.quran_type = type
	def __repr__(self):
		pass

aye_page_table = Table('aye_page_table',metadata,
		Column('aye_id',Integer,ForeignKey("aye_table.id"),primary_key=True),
		#Column('quran_type',Integer),
		Column('page_number',Integer, ForeignKey('page_table.page_number')))

page_table =  Table('page_table', metadata,
		Column('page_number', Integer, primary_key=True))


page_mapper = mapper(qPage, page_table)
aye_page_mapper = mapper(qPageNumber, aye_page_table,order_by=aye_page_table.c.aye_id,properties={'aye':relation(qpath.qAye,backref=backref('page',uselist=False)), 'page':relation(qPage, backref='page_ayat')})
aye_page_query = session.query(qPageNumber)
page_query = session.query(qPage)


def isSupportQuery(query,domain):
	r = re.compile("^\s*page{([^}]*)}\s*$").search(query)
	return (r != None)

def filter(query,domain):
	r = re.compile("^\s*page{([^}]*)}\s*$").search(query)
	result = []
	q = r.group(1).strip()
	r1 = re.compile("([0-9]*)\-([0-9]*)").search(q)
	if r1!=None:		
		if r1.group(1)=="":
			lowerbound = 1
		else:	
			lowerbound = int(r1.group(1))
		if r1.group(2)=="":
			upperbound = 100000
		else:	
			upperbound = int(r1.group(2))
	if q.isdigit():
		lowerbound = int(q)
		upperbound = int(q)
		

	for d in domain:
		if isinstance(d,qpath.qSure):
			if (d.ayat[0].page.page_number>=lowerbound) and (d.ayat[-1].page.page_number<=upperbound):
				result.append(d)
		if isinstance(d,qpath.qAye):
			if (d.page.page_number>=lowerbound) and (d.page.page_number<=upperbound):
				result.append(d)
		if isinstance(d,qpath.qWord):
			if (d.aye.page.page_number>=lowerbound) and (d.aye.page.page_number<=upperbound):
				result.append(d)
				
	return result

qpath.server_isSupports.append(isSupportQuery)
qpath.server_filter.append(filter)

if __name__ == "__main__":
	pass
